<template>
  <div class="customDialog">
    <div class="inStockDetail">
      <p style="font-size: 12px;margin-bottom: 10px;">产品明细</p>
      <el-button
        type="primary"
        size="mini"
        icon="el-icon-circle-plus-outline"
        class="addProduct"
        @click="addOrEditProduct"
      >添加产品</el-button>
      <el-button
        type="primary"
        size="mini"
        icon="el-icon-notebook-2"
        plain
        @click="$refs.bom.add({way:'addProduct'})"
      >按BOM添加</el-button>
      <!-- 列配置表格 -->
      <pop-checkbox
        :disposeGroup="disposeGroup"
        @handleChangeDiposeGroup="handleChangeDiposeGroup"
        style="float:right"
      ></pop-checkbox>
      <vxe-table
        show-overflow
        ref="xTable"
        row-id="uniqueId"
        border
        :data="productTable"
        :tree-config="{transform: true, rowField: 'uniqueId', parentField: 'parentId', expandAll: true}"
        :edit-config="{trigger: 'click', mode: 'row'}"
        :header-cell-style="{color:'#000',fontWeight:400,fontSize:'12px'}"
        :cell-style="{color:'#5a5a5a',fontSize:'12px',fontWeight:400}"
        :key="toUpdateTableKey"
      >
        <vxe-column
          v-for="(item,index) in tableGroup"
          :key="item.label"
          :title="item.name"
          :minWidth="item.width"
          :type="item.label == 'level' ? 'seq' : ''"
          :fixed="index <= 2 ? 'left' : ''"
        >
          <template #default="{ row , $rowIndex ,seq}">
            <code v-if="item.label == 'index'">{{$rowIndex + 1}}</code>
            <code v-else-if="item.label == 'level'">{{seq}}</code>
            <code
              v-else-if="item.label == 'unitUsage' || item.label == 'planedNumber'"
              @mouseenter="focusNumber($rowIndex, item.label)"
            >
              <el-input-number
                v-model="row[item.label]"
                controls-position="right"
                size="mini"
                @input.native="changeInputNumber"
                @change="changeNumber"
                @focus="focusNumber($rowIndex, item.label)"
                :min="item.label == 'unitUsage' ? 0 : 1"
                placeholder="请填写"
              ></el-input-number>
            </code>
            <code v-else-if="item.label == 'workOrderStartTimeAndEndTime'">
              <el-date-picker
                v-model="row[item.label]"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                format="yyyy-MM-dd HH:mm"
                :clearable="false"
                class="picker"
                end-placeholder="结束日期"
              ></el-date-picker>
            </code>
            <code v-else>
              <code v-if="customImgSet(item.label, row)">
                <p v-if="(JSON.parse(row[item.label])).length <= 2">
                  <img
                    :src="$global.uploadUrl + k.url"
                    alt
                    v-for="(k, i) in JSON.parse(row[item.label])"
                    :key="i"
                    class="customImg"
                    @click="costomImgPreview(i+1, (JSON.parse(row[item.label])).length, JSON.parse(row[item.label]))"
                  />
                </p>
                <p v-else>
                  <img
                    :src="$global.uploadUrl + JSON.parse(row[item.label])[0].url"
                    alt
                    class="customImg"
                    @click="costomImgPreview(1, JSON.parse(row[item.label]).length, JSON.parse(row[item.label]))"
                  />
                  <span class="customImgMoreBox">
                    <div
                      class="customImgMore"
                      @click="costomImgPreview(2, JSON.parse(row[item.label]).length, JSON.parse(row[item.label]))"
                    >
                      <el-popover placement="top" max-width="400" trigger="hover">
                        <div
                          class="customImgMore"
                          slot="reference"
                        >+{{ JSON.parse(row[item.label]).length - 2 }}</div>
                        <img
                          :src="$global.uploadUrl + k.url"
                          alt
                          v-for="(k, i) in JSON.parse(row[item.label])"
                          :key="i"
                          style="margin-right:10px"
                          width="60px"
                          height="60px"
                          @click="costomImgPreview(i+1, JSON.parse(row[item.label]).length, JSON.parse(row[item.label]))"
                        />
                      </el-popover>
                    </div>
                    <img
                      :src="$global.uploadUrl + JSON.parse(row[item.label])[1].url"
                      alt
                      class="customImg"
                    />
                  </span>
                </p>
              </code>
              <code v-else>
                <code v-if="customSelectSet(item.label,row)">
                  <span
                    v-for="(k, j) in customSelectList(item.label, row)"
                    :key="j"
                    :style="customSelectStyle(item.label, row, k)"
                    class="customSelect"
                  >{{ k }}</span>
                </code>
                <code v-else style="overflow: hidden;text-overflow: ellipsis;">{{row[item.label]}}</code>
              </code>
            </code>
          </template>
        </vxe-column>
        <vxe-column title="操作" fixed="right" width="150">
          <template #default="{ row , seq}">
            <vxe-button
              type="text"
              status="primary"
              @click="$refs.product.add({way:'addLevel',row})"
              :disabled="isGray(seq)"
            >添加子级</vxe-button>
            <vxe-button type="text" status="primary" @click="removeRow(row)">删除</vxe-button>
          </template>
        </vxe-column>
        <template #empty>
          <img src="@/assets/login/empty.png" style="width:100px;margin-top:10px" />
          <div style="color:#909399;line-height:60px;font-size:14px">暂无数据</div>
        </template>
      </vxe-table>
      <el-dialog :title="customImgData.title" :visible.sync="customImgData.visible" width="68%">
        <el-carousel
          trigger="click"
          height="50vh"
          :autoplay="false"
          :initial-index="customImgData.initial"
          @change="handleCarousel"
          ref="carousel"
        >
          <el-carousel-item v-for="(item, i) in customImgData.list" :key="i">
            <img :src="item.url" alt class="carouselImg" />
          </el-carousel-item>
        </el-carousel>
        <div class="imgDownLoad" @click="imgDownLoad">
          <span class="el-icon-download"></span>
          下载
        </div>
      </el-dialog>
    </div>

    <!-- 按BOM添加 -->
    <bom ref="bom" @getProductTable="getProductTable"></bom>

    <!-- 添加产品 -->
    <product ref="product" @getProductTable="getProductTable"></product>
  </div>
</template>

<script>
import { productColumns } from "@/api/customFieldController";
import bom from "./bom.vue";
import product from "./product.vue";
export default {
  props: {
    tableList: {
      type: Array,
      default: function() {
        return [];
      }
    }
  },
  data() {
    return {
      productTable: [],
      failData: [],
      tableGroup: [],
      disposeGroup: [],
      toUpdateTableKey: false,
      flattenTable: [],
      focusIndex: 0,
      labelIndex: "",
      customImgData: {
        visible: false,
        list: [],
        title: "",
        initial: 0,
        num: 0
      }
    };
  },
  components: {
    bom,
    product
  },
  computed: {
    isGray() {
      return seq => {
        console.log(seq);
        return seq.split(".").length >= 5;
      };
    }
  },
  watch: {
    tableList(nl, ol) {
      if (nl?.length > 0) {
        this.productTable = nl;
      }
    }
  },
  mounted() {
    this.getProductColumns({
      type: "assemblyDetail"
    });
  },
  methods: {
    changeNumber(nl, ol) {
      console.log(nl, ol);
      this.changeplaneNum(nl);
    },
    changeInputNumber(e) {
      console.log(e);
      let num = 1;
      if (e.target.value >= 1) {
        num = e.target.value;
      }
      this.changeplaneNum(num);
    },
    changeplaneNum(num) {
      this.utils.debounce(() => {
        const { tableData } = this.$refs.xTable.getTableData();
        console.log(num, tableData);
        if (
          this.labelIndex == "planedNumber" &&
          tableData[this.focusIndex] &&
          tableData[this.focusIndex].children?.length > 0
        ) {
          tableData.forEach(e => {
            console.log(e, this.focusIndex);
            let uniqueId = tableData[this.focusIndex].uniqueId.split(":")[0];
            let e_uniqueId = e.uniqueId.split(":")[0].substr(0, uniqueId.length);
            if (uniqueId == e_uniqueId) {
              e.planedNumber = parseInt(num) * e.unitUsage;
              tableData[this.focusIndex].planedNumber = num;
            }
          });
          // this.tableDataNum = tableData[this.focusIndex];
        } else if (this.labelIndex == "unitUsage") {
          console.log(num, tableData[this.focusIndex].planedNumber);
          let parentRow = this.$refs.xTable.getParentRow(
            tableData[this.focusIndex]
          );
          console.log(parentRow);
          if (parentRow) {
            // 根据单位修改数量
            //  tableData[this.focusIndex].planedNumber =  parseInt(num) * parentRow.planedNumber
          }
        }
      }, 100)();
    },

    focusNumber(i, label) {
      this.focusIndex = i;
      this.labelIndex = label;
    },

    getProductColumns: async function(data) {
      const res = await productColumns(data);
      if (res.code == 200) {
        this.disposeGroup = [];
        this.tableGroup = [];
        console.log(res.data);
        res.data.map((item, i) => {
          const key = {
            index: "80",
            level: "150",
            productCode: "150",
            productName: "120",
            productSpecification: "70",
            productAttribute: "70",
            productUnit: "50",
            finishNumber: "60",
            badProductNumber: "70",
            workOrderCode: "120",
            workOrderState: "70",
            workOrderStartTimeAndEndTime: "380"
          };
          let width = key[item.name] ?? "180";
          if (item.state) {
            this.tableGroup.push({
              label: item.name,
              name: item.chineseName,
              width
            });
          }
          this.disposeGroup.push({
            label: item.name,
            name: item.chineseName,
            state: item.state
          });
        });
      }
    },
    //监视复选框值变化
    handleChangeDiposeGroup(disposeGroup) {
      let configureList = [];
      configureList = disposeGroup.map(i => {
        return {
          name: i.label,
          chineseName: i.name,
          state: i.state
        };
      });
      this.getProductColumns({
        type: "assemblyDetail",
        configureList
      }).then(() => {
        this.updateTable();
      });
    },
    addOrEdit(payload) {
      this.$refs.addOrEdit.add(payload);
    },
    addOrEditProduct(payload) {
      let uniqueId = 1;
      const { tableData } = this.$refs.xTable.getTableData();
      try {
        if (tableData?.length > 0) {
          uniqueId = tableData.length;
        }
      } catch (e) {
        console.log(e);
      }
      console.log(uniqueId);
      this.$refs.product.add({ way: "addProduct" }, uniqueId);
    },
    extractTree(arrs, childs, attrArr) {
      let attrList = [];
      if (!Array.isArray(arrs) && !arrs.length) return [];
      if (typeof childs !== "string") return [];
      if (
        !Array.isArray(attrArr) ||
        (Array.isArray(attrArr) && !attrArr.length)
      ) {
        attrList = Object.keys(arrs[0]);
      } else {
        attrList = attrArr;
      }
      let list = [];
      const getObj = arr => {
        arr.forEach(function(row) {
          let obj = {};
          attrList.forEach(item => {
            obj[item] = row[item];
          });
          list.push(obj);
          if (row[childs]) {
            getObj(row[childs]);
          }
        });
        return list;
      };
      return getObj(arrs);
    },
    handleEmit(productTable) {
      //将数组扁平化
      this.flattenTable = productTable.length
        ? this.extractTree(productTable, "children")
        : [];
      setTimeout(() => {
        this.flattenTable.forEach(i => {
          //给每条数据添加上相应的层级
          i.level = this.$refs.xTable.getRowSeq(i);
        });
        console.log(this.flattenTable, this.productTable);
        this.$nextTick(() => {
          // this.productTable = [...this.flattenTable]
          // console.log(this.productTable );
        });
      }, 100);
      // this.$emit('productTableList', this.flattenTable)
    },

    getFlattenTable() {
      console.log(
        this.productTable,
        this.flattenTable,
        this.$refs.xTable.getTableData()
      );
      let resTable = this.$refs.xTable.getTableData();
      resTable.tableData.forEach(i => {
        //给每条数据添加上相应的层级
        i.level = this.$refs.xTable.getRowSeq(i);
      });
      console.log(resTable);
      return resTable.tableData;
    },

    //添加BOM:明细列表数据
   async getProductTable(payload, info) {
      console.log(payload, info);
      const { way, row } = info;
      let $table = this.$refs.xTable

      if (way === "addLevel") {
        //添加子级
        this.insertRow(row, payload.productTable, productTable => {
          const { tableData } = $table.getTableData();
          tableData.forEach(e => {
            let level = $table.getRowSeq(e);
            console.log(level);
            e.level = level;
            e.uniqueId = level + ":" + e.uniqueId.split(":")[1];
          });
          console.log(tableData);
          this.productTable = [...tableData];
        });
      
      } else {
        let productTable = [];
        const { tableData } = $table.getTableData();
        tableData.forEach(e => {
          let level = $table.getRowSeq(e);
          e.level = level;
          e.uniqueId = level + ":" + e.uniqueId.split(":")[1];
        });
        console.log(tableData);
        productTable = payload.productTable;
        if (tableData.length > 0) {
          let parentRow = $table.getParentRow(
            tableData[tableData.length - 1]
          );
          console.log(parentRow);
          // 给每条数据添加上相应的层级
          // i.level = this.$refs.xTable.getRowSeq(tableData[tableData.length - 1]);
          try {
            let uniqueId = 0;
            if (parentRow?.uniqueId) {
              uniqueId = parentRow.uniqueId.split(":")[0];
            } else {
              uniqueId = tableData[tableData.length - 1].uniqueId;
              console.log(uniqueId);
              if (uniqueId && uniqueId.split(":").length >= 1) {
                uniqueId = (uniqueId + "").split(".")[0];
              }
            }
            console.log(tableData[tableData.length - 1], uniqueId);
            let rowi = parseInt(uniqueId);
            if (payload.productTable.length > 1) {
              productTable = this.changeLevel(payload.productTable, rowi);
            } else {
              productTable = this.changeProductLevel(payload.productTable, rowi)
            }
            console.log(productTable);
          } catch (e) {
            console.log(e);
          }
        } else {
          if (productTable?.length) {
            productTable.forEach(async e => {
              await $table.insertAt(e, -1);
              await $table.setTreeExpand(e, true); // 将父节点展开
            })
          }
        }
        console.log(productTable, tableData);
        if (productTable?.length) {
          // this.productTable = [...this.productTable, ...productTable];
          this.productTable = [...tableData, ...productTable];
        }
      }
      this.handleEmit(this.productTable);
    },
    // // 添加产品：明细列表数据
    // getProductTable(payload, info) {
    //   console.log(payload, info);
    //   const { way, row } = info;
    //   if (way === "addLevel") {
    //     //添加子级
    //     this.insertRow(row, payload.productTable, productTable => {});
    //   } else {
    //     let productTable = [];
    //     const { tableData } = this.$refs.xTable.getTableData();
    //     console.log(tableData);
    //     productTable = payload.productTable;
    //     if (tableData.length > 0) {
    //       let parentRow = this.$refs.xTable.getParentRow(
    //         tableData[tableData.length - 1]
    //       );
    //       console.log(parentRow);
    //       try {
    //         let rowi = parseInt(parentRow.uniqueId.split(":")[0]);
    //         productTable = this.changeLevel(payload.productTable, rowi);
    //         console.log(productTable);
    //       } catch (e) {
    //         console.log(e);
    //       }
    //     }
    //     this.productTable = [...this.productTable, ...productTable];
    //   }
    //   this.handleEmit(this.productTable);
    // },

    changeLevel(list, rowi) {
      const $table = this.$refs.xTable;
      console.log(list);
      if (list.length > 1) {
        list.forEach(async e => {
          if (e.uniqueId.indexOf(".") >= 0) {
            e.uniqueId =
              rowi +
              1 +
              e.uniqueId.slice(e.uniqueId.indexOf("."), e.uniqueId.length);
            e.level = e.uniqueId.split(":")[0];
            if (e.parentId && e.parentId.indexOf(".") >= 0) {
              e.parentId =
                rowi +
                1 +
                e.parentId.slice(e.parentId.indexOf("."), e.parentId.length);
            } else {
              e.parentId = rowi + 1 + ":" + e.parentId.split(":")[1];
            }
          } else {
            e.uniqueId = rowi + 1 + ":" + e.uniqueId.split(":")[1];
            e.level = e.uniqueId.split(":")[0];
          }
          await $table.insertAt(e, -1);
          await $table.setTreeExpand(e, true); // 将父节点展开
        });
      }
      console.log(list);
      return list;
    },

    async changeProductLevel(list, rowi) {
      const $table = this.$refs.xTable;
      let e = list[0];
      e.uniqueId = rowi + 1 + ":" + e.uniqueId.split(":")[1];
      e.level = e.uniqueId.split(":")[0];
      await $table.insertAt(e, -1);
      await $table.setTreeExpand(e, true); // 将父节点展开
      return list;
    },

    async insertRow(currRow, record, callback) {
      console.log(currRow, record);
      const $table = this.$refs.xTable;
      const { row: newRow } = await $table.insertAt(record, -1);
      console.log(newRow);
      await $table.setTreeExpand(currRow, true); // 将父节点展开
      await $table.setActiveRow(newRow); // 插入子节点
      callback(newRow);
    },
    removeRow(row) {
      this.$confirm("操作将同时删除下级产品", "确认删除产品？", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        customClass: "messagebox",
        confirmButtonClass: "dangerBtn",
        type: "warning"
      })
        .then(async () => {
          const $table = this.$refs.xTable;
          await $table.remove(row);
          let tables = $table.getTableData();
          try {
            tables.forEach(async e => {
            if (e.parentId == row.uniqueId) {
              await $table.remove(e);
            }
          })
          } catch (error) {
            
          }
          // const removeUniId = $table.getRemoveRecords().map(i => i.uniqueId);
          // removeUniId.length &&
          //   (this.productTable = this.productTable.filter(
          //     i => !removeUniId.includes(i.uniqueId)
          //   ));
          if (row.id) {
            this.$emit("handleDelete", row.id);
          }
          this.handleEmit(this.productTable);
        })
        .catch(() => {});
    },
    //跳转至详情页面
    cellClick(row, column) {
      if (column.label == "工单编号" && row.workOrderCode != "待生成") {
        this.$router.push({
          path: "/productionManagement/edit",
          query: {
            id: row.workOrderId,
            code: row.workOrderCode,
            state: row.workOrderState,
            salesId: row.salesId,
            salesCode: row.salesCode
          }
        });
      }
    },
    // 自定义字段 复选框/单选框 列
    customSelectSet(t, d) {
      let state = false;
      if (d.customFieldVos != null) {
        d.customFieldVos.map(item => {
          if (item.customFieldMess != null) {
            if (
              (item.customFieldMess.fieldType == "selectRadio" ||
                item.customFieldMess.fieldType == "selectChecked") &&
              t == item.customFieldId
            ) {
              state = true;
            }
          }
        });
        return state;
      } else {
        return false;
      }
    },
    customSelectList(t, d) {
      if (d[t] == "" || d[t] == "[]") {
        return [];
      } else {
        let data = [];
        try {
          data = JSON.parse(d[t]);
        } catch {
          data = d[t].split(",");
          data[0] == "" ? (data = []) : "";
        }
        data === Number(data) ? (data = [data]) : "";
        return data;
      }
    },
    customSelectStyle(t, d, v) {
      let style = {};
      if (d.customFieldVos != null) {
        let obj = d.customFieldVos.find(res => {
          return res.customFieldId == t;
        });
        if (obj.value != "" && obj.value != "[]") {
          if (obj.customFieldMess.fieldType == "selectRadio") {
            let color = JSON.parse(obj.customFieldMess.checkBox).find(res => {
              return obj.value == res.value;
            });
            if (color != undefined) {
              return {
                color: color.color,
                background:
                  color.color.substr(0, 3) +
                  "a" +
                  color.color.substr(3, color.color.length - 4) +
                  ", .1)"
              };
            } else {
              return {
                color: "#333",
                background: "#f4f4f5"
              };
            }
          }
          if (obj.customFieldMess.fieldType == "selectChecked") {
            let color = JSON.parse(obj.customFieldMess.checkBox).find(res => {
              return v == res.value;
            });
            if (color != undefined) {
              return {
                color: color.color,
                background:
                  color.color.substr(0, 3) +
                  "a" +
                  color.color.substr(3, color.color.length - 4) +
                  ", .1)"
              };
            } else {
              return {
                color: "#333",
                background: "#f4f4f5"
              };
            }
          }
        }
      }
    },
    // 自定义字段图片列
    customImgSet(t, d) {
      let state = false;
      if (d.customFieldVos != null) {
        d.customFieldVos.map(item => {
          if (item.customFieldMess != null) {
            if (
              item.customFieldMess.fieldType == "picture" &&
              t == item.customFieldId
            ) {
              state = true;
            }
          }
        });
        return state;
      } else {
        return false;
      }
    },
    // 自定义图片预览
    costomImgPreview(i, len, list) {
      this.customImgData.visible = true;
      this.customImgData.title = "预览" + " (" + i + "/" + len + ")";
      this.customImgData.initial = Number(i) - 1;
      this.customImgData.list = list.map(item => {
        return {
          name: item.name,
          url: this.$global.uploadUrl + item.url
        };
      });
      this.customImgData.num = i - 1;
      this.setActiveItem(i - 1);
    },
    setActiveItem(i) {
      if (this.$refs.carousel) {
        this.$refs.carousel.setActiveItem(i);
      }
    },
    // 图片预览轮播切换
    handleCarousel(v) {
      this.customImgData.title =
        "预览" +
        " (" +
        (Number(v) + 1) +
        "/" +
        this.customImgData.list.length +
        ")";
      this.customImgData.num = v;
    },
    // 图片下载
    imgDownLoad() {
      window.open(
        this.customImgData.list[this.customImgData.num].url,
        "_blank"
      );
    },
    updateTable() {
      this.toUpdateTableKey = !this.toUpdateTableKey;
    }
  }
};
</script>

<style lang="less" scoped>
.inStockDetail {
  code {
    font-family: sans-serif;
  }

  .addProduct {
    margin-bottom: 10px;
  }

  .icon-wenhao {
    margin-left: 2px;
    vertical-align: bottom;
  }
}

.el-dialog.failD {
  .el-dialog__header {
    .fail {
      width: 210px;
      height: 55px;
      display: flex;
      align-items: center;
      justify-content: space-between;

      ::v-deep .el-result {
        padding: 0;
        align-items: flex-start;

        .el-result__icon svg {
          width: 40px;
          height: 40px;
        }
      }
    }
  }
}
.status {
  span {
    display: inline-block;
    vertical-align: middle;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    color: #409eff;
    cursor: pointer;
  }
}
::v-deep .el-range-editor.el-input__inner {
  height: 30px;
  line-height: 30px;
}
::v-deep.el-date-editor .el-range__icon,
::v-deep .el-date-editor .el-range-separator {
  line-height: 22px;
}

::v-deep .el-dialog__body {
  padding: 10px 20px;
}

::v-deep .el-dialog__footer {
  text-align: center;
}

::v-deep .el-select {
  width: 100%;
}

::v-deep .el-input-number--mini {
  width: 100%;
}

::v-deep .el-date-editor.el-input {
  width: 100%;
}

::v-deep .el-range-editor.el-input__inner {
  width: 100%;
}
::v-deep .el-range-editor .el-range-input {
  flex: 3;
}
::v-deep .el-date-editor .el-range-separator {
  flex: 1;
}
</style>